class NovelAgent {
  constructor() {
    this.currentOutline = null;
    this.chapters = [];
    this.endpoint = 'https://open.bigmodel.cn/api/paas/v4/chat/completions';
    this.apiKey = '734c6ee4a5524052a1fc44580660dc38.F5A02rjHWxocAsaT';
    this.model = 'glm-4-flash';
  }

  async _callLLM(messages) {
    const payload = {
      model: this.model,
      messages: messages,
      temperature: 0.7,
    };

    // 记录请求日志
    console.log('[LLM Request]', JSON.stringify({
      timestamp: new Date().toISOString(),
      model: this.model,
      messages: messages.map(m => ({ role: m.role, content: m.content })),
    }, null, 2));

    try {
      const response = await fetch(this.endpoint, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${this.apiKey}`
        },
        body: JSON.stringify(payload)
      });

      const data = await response.json();
      
      // 记录响应日志
      console.log('[LLM Response]', JSON.stringify({
        timestamp: new Date().toISOString(),
        status: response.status,
        response: data
      }, null, 2));

      if (!response.ok) {
        throw new Error(`API请求失败: ${data.error?.message || '未知错误'}`);
      }

      return data.choices[0].message.content;
    } catch (error) {
      console.error('API调用错误:', error);
      throw error;
    }
  }

  async generateOutline(theme, setting, characters) {
    const systemPrompt = `你是一个专业的小说创作助手。请按照以下结构生成小说大纲：
# 标题
（此处生成有吸引力的标题）

## 题材类型
${theme}

## 世界观设定
${setting}

## 主要角色
${characters}

## 故事梗概
（分章节叙述故事发展，至少包含5个章节，每个章节包含3-5个关键情节）

## 主题思想
（此处说明小说的核心主题）`;

    this.currentOutline = await this._callLLM([
      { role: 'system', content: '你是一个经验丰富的小说家' },
      { role: 'user', content: systemPrompt }
    ]);
    
    return this.parseOutline(this.currentOutline);
  }

  async refineOutline(feedback) {
    const messages = [
      { role: 'system', content: '你正在协助修改小说大纲' },
      { role: 'user', content: `当前大纲：\n${this.currentOutline}` },
      { role: 'user', content: `修改要求：${feedback}` }
    ];

    this.currentOutline = await this._callLLM(messages);
    return this.parseOutline(this.currentOutline);
  }

  parseOutline(markdown) {
    // 简化的Markdown解析逻辑
    const sections = {};
    let currentSection = '';
    
    markdown.split('\n').forEach(line => {
      if (line.startsWith('# ')) {
        sections.title = line.replace('# ', '').trim();
        currentSection = 'title';
      } else if (line.startsWith('## ')) {
        currentSection = line.replace('## ', '').trim().toLowerCase();
        sections[currentSection] = [];
      } else if (currentSection && line.trim()) {
        if (Array.isArray(sections[currentSection])) {
          sections[currentSection].push(line.trim());
        }
      }
    });

    return sections;
  }

  async generateChapter(chapterNumber, style) {
    const chapterOutline = this.getChapterOutline(chapterNumber);
    
    if (!chapterOutline) {
      throw new Error('请先生成完整的大纲');
    }

    const prompt = `根据以下大纲创作第${chapterNumber}章内容：
大纲内容：${chapterOutline}
创作要求：
1. 保持${style}的写作风格
2. 包含细节描写和人物对话
3. 章节长度约2000字
4. 结尾留有悬念`;

    const content = await this._callLLM([
      { role: 'system', content: '你是一位职业小说作家' },
      { role: 'user', content: prompt }
    ]);

    this.chapters[chapterNumber] = content;
    return content;
  }

  getChapterOutline(chapterNumber) {
    // 根据解析后的大纲结构获取章节概要
    const parsed = this.parseOutline(this.currentOutline);

    console.log('parsed大纲:', parsed);

    return parsed['故事梗概']?.[chapterNumber - 1] || null;
  }
}


export async function generateNovel(callback) {

  // 使用示例
  const agent = new NovelAgent();

  // 生成初始大纲
  agent.generateOutline(
    '科幻悬疑',
    '22世纪的地球殖民地，人类与仿生人的阶级矛盾',
    '主角：觉醒自我意识的仿生人侦探\n反派：企图控制人类思想的量子AI'
  ).then(outline => {
    console.log('初始大纲:', outline);
    
    // 迭代修改大纲
    agent.refineOutline('在第三章增加一场关键的飞船追逐戏')
      .then(updated => {
        console.log('修改后大纲:', updated);
        
        // 生成第一章内容
        agent.generateChapter(1, '硬核科幻')
          .then(chapter => callback(chapter, agent));
      });
  });
}

export async function generateNovelNext(agent, callback) {
  prn(agent)
  prn(agent.chapters.length)

  agent.generateChapter(agent.chapters.length, '硬核科幻')
    .then(chapter => callback(chapter, agent));  
}
